package com.nebula.task;

import com.nebula.entity.Orders;
import com.nebula.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

//记得加入bean容器
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    //每分钟处理一次超时未支付订单
    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeOutOrder() {
        //输出日志
        log.info("定时处理超时订单：{}}", LocalDateTime.now());

        //查询出超时的订单
        Integer status = Orders.PENDING_PAYMENT;
        LocalDateTime orderTime = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(status, orderTime);

        //修改超时订单状态为取消，添加取消时间，取消原因
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时");
                orderMapper.update(orders);
            }
        }
    }

    //每天凌晨一点处理一次一直派送中订单
    @Scheduled(cron = "0 0 2 * * ?")
    public void processDeliverOrder() {
        //输出日志
        log.info("处理一直派送中订单；{}", LocalDateTime.now());

        //查询状态为派送中的订单
        LocalDateTime orderTime = LocalDateTime.now().minusHours(2);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, orderTime);

        //修改订单状态为完成并更新订单表
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
